/// 可享资源页面
/// 
/// 显示其他用户授权给我查看的视频集合列表
/// 用于用户购买或被授权访问的视频集合
/// 
/// @author Matrix
/// @version 1.0.0
/// @since 2025-11-27

import 'package:flutter/material.dart';
import '../../models/collection_model.dart';
import '../../services/collection_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'collection_detail_page.dart';

/// 可享资源页面
/// 
/// 显示被授权访问的视频集合列表
class SharedResourcesPage extends StatefulWidget {
  const SharedResourcesPage({super.key});

  @override
  State<SharedResourcesPage> createState() => _SharedResourcesPageState();
}

class _SharedResourcesPageState extends State<SharedResourcesPage> {
  /// 集合服务
  final CollectionService _collectionService = CollectionService();
  
  /// 集合列表
  List<CollectionModel> _collections = [];
  
  /// 是否正在加载
  bool _isLoading = false;
  
  /// 是否有更多数据
  bool _hasMore = true;
  
  /// 当前页码
  int _currentPage = 1;
  
  /// 每页数量
  static const int _pageSize = 20;

  @override
  void initState() {
    super.initState();
    _loadSharedCollections(refresh: true);
  }

  /// 加载授权的集合列表
  Future<void> _loadSharedCollections({bool refresh = false}) async {
    if (_isLoading) return;
    if (!refresh && !_hasMore) return;

    setState(() => _isLoading = true);

    try {
      if (refresh) {
        _currentPage = 1;
        _hasMore = true;
      }

      final result = await _collectionService.getSharedCollections(
        page: _currentPage,
        pageSize: _pageSize,
      );

      setState(() {
        if (refresh) {
          _collections = result.records;
        } else {
          _collections.addAll(result.records);
        }
        _hasMore = result.hasMore;
        if (result.hasMore) {
          _currentPage++;
        }
        _isLoading = false;
      });

      Logger.d('SHARED_RESOURCES', '加载成功，共 ${_collections.length} 个集合');
    } catch (e) {
      Logger.e('SHARED_RESOURCES', '加载集合列表失败: $e');
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e')),
        );
      }
    }
  }

  /// 刷新列表
  Future<void> _refresh() async {
    await _loadSharedCollections(refresh: true);
  }

  /// 查看集合详情
  void _viewCollection(CollectionModel collection) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CollectionDetailPage(
          collection: collection,
          isSharedView: true, // 标记为共享视图，只读模式
        ),
      ),
    ).then((result) {
      if (result == true) {
        _refresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('可享资源'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 说明文字
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            color: Colors.blue[50],
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue[700], size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    '这里显示其他用户授权给您查看的视频集合，包括购买的付费内容和白名单授权的资源',
                    style: TextStyle(
                      fontSize: 13,
                      color: Colors.blue[700],
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          // 集合列表
          Expanded(
            child: _buildCollectionList(),
          ),
        ],
      ),
    );
  }

  /// 构建集合列表
  Widget _buildCollectionList() {
    if (_isLoading && _collections.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_collections.isEmpty) {
      return _buildEmptyState();
    }

    return RefreshIndicator(
      onRefresh: _refresh,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _collections.length + (_hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _collections.length) {
            // 加载更多
            if (_hasMore && !_isLoading) {
              _loadSharedCollections();
            }
            return const Center(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: CircularProgressIndicator(),
              ),
            );
          }
          return _buildCollectionCard(_collections[index]);
        },
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.video_library_outlined,
            size: 80,
            color: Colors.grey[300],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无可享资源',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '当其他用户授权您访问视频集合时，会显示在这里',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[400],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// 构建集合卡片
  Widget _buildCollectionCard(CollectionModel collection) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: InkWell(
        onTap: () => _viewCollection(collection),
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 封面图
              ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: CachedImageWidget(
                  imageUrl: collection.coverUrl,
                  width: 100,
                  height: 75,
                  fit: BoxFit.cover,
                  imageType: '集合封面',
                ),
              ),
              const SizedBox(width: 12),
              
              // 集合信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                      collection.title,
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    
                    // 作者信息
                    Row(
                      children: [
                        Icon(Icons.person, size: 14, color: Colors.grey[600]),
                        const SizedBox(width: 4),
                        Text(
                          collection.userNickname ?? '未知作者',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    
                    // 描述
                    if (collection.description != null && collection.description!.isNotEmpty)
                      Text(
                        collection.description!,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey[600],
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 8),
                    
                    // 统计信息
                    Row(
                      children: [
                        _buildStatItem(Icons.video_library, '${collection.videoCount}个视频'),
                        const SizedBox(width: 16),
                        _buildStatItem(Icons.visibility, '${collection.viewsCount}浏览'),
                        const Spacer(),
                        // 授权类型标识
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.green[100],
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.check_circle, size: 12, color: Colors.green[700]),
                              const SizedBox(width: 4),
                              Text(
                                '已授权',
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Colors.green[700],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              
              // 查看按钮
              Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(IconData icon, String text) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 14, color: Colors.grey[500]),
        const SizedBox(width: 4),
        Text(
          text,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }
}
